#将爬取的数据存储到postgresql数据库中
from models.serp import  SerpResult
from extensions.ext_database import db

class StoreData:
    #data参数格式必须是dict
    @staticmethod
    def store_google(data):
        try:
            for result in data['organic_results']:
                serp = SerpResult()
                serp.position = result['position']
                serp.title = result['title']
                serp.link = result['link']
                serp.source = result.get('source', 'N/A')
                serp.date = result.get('date', 'N/A')
                serp.snippet = result.get('snippet', 'N/A')
                if not StoreData.is_duplicate(serp.title):
                    db.session.add(serp)
                    db.session.commit()
                else:
                    print("数据重复，不插入数据库")
            return True

        except KeyError as  e:
            print('存入数据库异常')
            return False

    @staticmethod
    def is_duplicate(result_title):
        serp_result = SerpResult.query.filter_by(title=result_title).first()
        # 如果存在相等的记录，则返回 True，否则返回 False

        return serp_result is not None



